/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.action.organization;

import apus.action.Action;
import apus.action.ActionResult;
import apus.entity.Organization;
import apus.entity.RealOrganization;
import apus.exception.EntityNotFoundException;
import apus.persistence.OrganizationDAO;
import apus.services.ServiceLocator;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author 21vek
 */
public class OrganizationDeleteAction implements Action {

    @Override
    public String getName() {
        return "organization.delete";
    }

    @Override
    public ActionResult execute(HttpServletRequest request, HttpServletResponse response) {
        if (request.getParameter("id") != null) {
            int id = Integer.parseInt(request.getParameter("id"));
            Organization organization = new RealOrganization();
            organization.setId(id);
            ServiceLocator.getService(OrganizationDAO.class).delete(organization);
            request.getSession().setAttribute("win", request.getParameter("name") + " was removed");
        } else {
            request.getSession().setAttribute("fail", "Organization wasn't removed");
        }

        

        List<Organization> organizationList;
        if (request.getParameter("name") != null) {
            request.getSession().setAttribute("searchQuery", request.getParameter("name"));
            try {
                organizationList = ServiceLocator.getService(OrganizationDAO.class).readByName(request.getParameter("name"), 1);
            } catch (EntityNotFoundException e) {
                organizationList = new ArrayList<Organization>();
            }
        } else {
            organizationList = ServiceLocator.getService(OrganizationDAO.class).findAll();
        }
        //List<Organization> organizationList = ServiceLocator.getService(OrganizationDAO.class).findAll();

        request.setAttribute("organizationList", organizationList);
        return ActionResult.redirect("organization.list");
    }
}
